'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Users extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  Users.init({
    username: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notEmpty: { msg: '用户名不能为空' },
        notNull: { msg: '用户名不能为空' },
        len: { args: [2, 10], msg: '用户名的长度必须在2到10之间' },
        async isUniqueUsername(value) {
          const count = await Users.count({ where: { username: value } });
          if (count > 0) {
            throw new Error('用户名已存在');
          }
        }
      }
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notEmpty: { msg: '密码不能为空' },
        notNull: { msg: '密码不能为空' },
        len: { args: [6, 16], msg: '密码的长度必须在6到16之间' }}
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notEmpty: { msg: '邮箱不能为空' },
        notNull: { msg: '邮箱不能为空' },
        isEmail: { msg: '邮箱格式不正确' },
        async isUniqueEmail(value) {
          const count = await Users.count({ where: { email: value } });
          if (count > 0) {
            throw new Error('邮箱已存在');
          }
        },
      }
    },
    role: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notEmpty: { msg: '角色不能为空' },
        notNull: { msg: '角色不能为空' },
        isIn: { args: [[0, 100]], msg: '角色的值是，普通用户:0,超级管理员:100' }
      }
    },
    introduction: DataTypes.TEXT,
    avatar: {
      type: DataTypes.STRING,
      validate:{
        isUrl: {
          msg: '头像链接必须是一个url'
        }
      }
    },
    company: DataTypes.STRING,
    nickname: DataTypes.STRING,
    sex: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notEmpty: { msg: '性别不能为空' },
        notNull: { msg: '性别不能为空' },
        isIn: { args: [[0, 1, 2]], msg: '性别的值是，男性:0,女性:1,未选择:2' }
      }
    }
  }, {
    sequelize,
    modelName: 'Users',
  });
  return Users;
};